#!/bin/bash

set -e

user_list=$1

if [[ $user_list == "" ]];
then
  echo "Usage: ./check-cluster-autoback.sh \"'usr-xxx'\""
  echo "       lots of users use: \"'usr-xxx','usr-yyy'\""
  exit 1
fi

shell_pwd=$(cd "$( dirname "$0" )" && pwd)
if [ ! -d "${shell_pwd}/logs" ];
then
  mkdir ${shell_pwd}/logs
fi
log_date=$(date +'%Y%m%d-%H-%M-%S')
sql_cli="/pitrix/bin/exec_sql.py -d zone -c"
get_clster_sql="select cluster_id,root_user_id,auto_backup_time from cluster where root_user_id in (${user_list}) and status='active' and app_id!='app-qingcloud-appcenter-metadata'"
${sql_cli} "${get_clster_sql}" 2>/dev/null|grep 'cl-' >${shell_pwd}/logs/all_cluster.txt
cluster_zone=($(awk '{print $2}' ${shell_pwd}/logs/all_cluster.txt))
user_zone=($(awk '{print $4}' ${shell_pwd}/logs/all_cluster.txt))
auto_back_zone=($(awk '{print $6}' ${shell_pwd}/logs/all_cluster.txt))
num=$(wc -l < ${shell_pwd}/logs/all_cluster.txt)
echo "集群ID 用户ID 是否配置自动备份 最近一次成功备份的时间" >${shell_pwd}/logs/check_auto_back.log.${log_date}

for ((times=0;times<${num};times++));
do
  cluster_id=${cluster_zone[$times]}
  user_id=${user_zone[$times]}
  auto_back=${auto_back_zone[$times]}
  if [[ $(awk 'BEGIN{print('${auto_back}'>=0)?"0":"1"}') -eq 0 ]];
  then
    auto_back_status="yes"
    last_job_sql="select status_time from job where resource_ids='${cluster_id}' and status='successful' and job_action='BackupResources' and create_time=(select max(create_time) from job where resource_ids in ('${cluster_id}') and status='successful' and job_action='BackupResources');"
    last_time=$(${sql_cli} "${last_job_sql}" 2>/dev/null|grep ' 20'|awk '{OFS="_";print $2,$3}')
    echo "${cluster_id} ${user_id} ${auto_back_status} ${last_time}" >>${shell_pwd}/logs/check_auto_back.log.${log_date}
  else
    auto_back_status="no"
    echo "${cluster_id} ${user_id} ${auto_back_status}" >>${shell_pwd}/logs/check_auto_back.log.${log_date}
  fi

done

column -t < ${shell_pwd}/logs/check_auto_back.log.${log_date}
